﻿using Spring.Aop;
using Spring.Aop.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;

namespace OpenApi
{
	public class AopInstanceProvider : IInstanceProvider
	{
		Type serviceType;

		public AopInstanceProvider(Type serviceType)
		{
			this.serviceType = serviceType;
		}

		public object GetInstance(InstanceContext instanceContext, Message message)
		{
			ProxyFactory proxyFactory = new ProxyFactory(Activator.CreateInstance(serviceType));
			proxyFactory.AddAdvice(new AopInterceptor());
			return proxyFactory.GetProxy();
		}

		public object GetInstance(InstanceContext instanceContext)
		{
			return GetInstance(instanceContext, null);
		}

		public void ReleaseInstance(InstanceContext instanceContext, object instance)
		{
			if (instance is IDisposable)
			{
				((IDisposable)instance).Dispose();
			}
		}
	}
}
